set scheme cleanplots
set varabbrev on

** Window selection

use "$project_path/data/4_regdata/regdata", clear

//We test for all covariates jointly using Hotelling's T^2 test.
rdwinselect runvar lagged_growth_gdpc_penn lagged_inflation_imf lagged_unemployment_ilo lagged_trade_wb lagged_hdi lagged_democracy_index last_treatment last_runvar, stat(hotelling) seed(1234) 

local selected_window = r(w_right)

** Inference

foreach v in diff_m1_chix_econ std_diff_m1_hdi std_diff_m1_democracy_index diff_m1_general_chix {
	//We run the test
	rdrandinf `v' runvar, wl(-`selected_window') wr(`selected_window') seed(1234)
	//We store the estimated p-value
	local pv_`v' : dis %5.3f `r(randpval)'
	if `r(randpval)'<0.001 local pv_`v' = "< 0.001"
	if `r(randpval)'>=0.001 local pv_`v' = "= `pv_`v''" 
	//We store the diff in means estimate
	local est_`v' : dis %5.3f `r(obs_stat)'
}

**	Sensitivity analysis

foreach v in diff_m1_chix_econ std_diff_m1_hdi std_diff_m1_democracy_index diff_m1_general_chix {
	
use "$project_path/data/4_regdata/regdata", clear
keep Country Year Month Type_Election `v' runvar
	
if "`v'"=="diff_m1_chix_econ" local vartitle = "Economic performance"
if "`v'"=="std_diff_m1_hdi" local vartitle = "Human Development Index"
if "`v'"=="std_diff_m1_democracy_index" local vartitle = "Democracy"
if "`v'"=="diff_m1_general_chix" local vartitle = "General index"

if "`v'"=="diff_m1_chix_econ" local filename = "Appendix_Figure_F1a"
if "`v'"=="std_diff_m1_hdi" local filename = "Appendix_Figure_F1b"
if "`v'"=="std_diff_m1_democracy_index" local filename = "Appendix_Figure_F1c"
if "`v'"=="diff_m1_general_chix" local filename = "Appendix_Figure_F1d"

rdsensitivity `v' runvar, wlist(0.5(0.05)10) tlist(-0.2(0.05)0.6) seed(1234) nodots saving("$project_path/output/appendix_figures/graphdata") 

use "$project_path/output/appendix_figures/graphdata", clear
lab var w "Window"
lab var t "Treatment effect"
lab var pvalue "p-value"
sort w t
by w : egen max_pval = max(pvalue)
gen max_att = (max_pval == pval)

twoway 	(contourline pvalue t w, ccuts(0.1) ccolor(navy)  yline(0)) (line t w if max_att==1, lpattern(dash)), ylabel(-0.2(0.2)0.6) note("Point estimate at optimally chosen window: `est_`v'' (p-val. `pv_`v'')", tstyle(size(medlarge))) xline(`selected_window', lcolor(red)) xtitle("Window", size(large))  ytitle("Treatment effect", size(large)) title("`vartitle'", size(vlarge)) graphregion(color(white)) xlabel(, labsize(large)) ylabel(, labsize(large)) plegend(off)
graph export "$project_path/output/appendix_figures/`filename'.pdf", as(pdf) name("Graph") replace

erase "$project_path/output/appendix_figures/graphdata.dta"

}

set varabbrev off
set scheme s2color
